<template>
	<view class="verify-code-page">
		<!-- 关闭按钮 -->
		<view class="close-btn" @click="onClose">
			<uni-icons type="closeempty" size="20"></uni-icons>
		</view>

		<!-- 标题 -->
		<view class="title">输入验证码</view>

		<!-- 提示信息 -->
		<view class="tips">验证码已发送至 +86 {{ formattedPhone }}</view>

		<!-- 验证码输入框 -->
		<view class="code-input-box">
			<view class="code-item" v-for="(item, index) in 4" :key="index"
				:class="{ active: index === verificationCode.length && !isCodeError, error: isCodeError && index < verificationCode.length, filled: index < verificationCode.length && !isCodeError }">
				<text class="code-text">{{ verificationCode[index] || '' }}</text>
			</view>
		</view>

		<!-- 自定义数字键盘 -->
		<view class="custom-keyboard" v-if="showKeyboard">
			<view class="keyboard-row" v-for="(row, rowIndex) in keyboardLayout" :key="rowIndex">
				<view class="key" v-for="(key, keyIndex) in row" :key="keyIndex" @click="onKeyClick(key)">
					{{ key }}
				</view>
			</view>
			<view class="keyboard-row">
				<view class="key empty"></view>
				<view class="key" @click="onKeyClick('0')">0</view>
				<view class="key delete" @click="onDelete">删除</view>
			</view>
		</view>

		<!-- 重新获取倒计时 -->
		<view class="count-down">
			<text v-if="!isCountdownEnd" :style="{ color: '#A3A6B7' }">{{ countDown }}'后可重新获取</text>
			<text v-else @click="onRegetCode" :style="{ color: '#1890FF', cursor: 'pointer' }">重新获取验证码</text>
		</view>
	</view>
</template>

<script>
// 导入request工具
import { request } from '../../utils/request';

export default {
	data() {
		return {
			phoneNumber: '',
			verificationCode: '',
			countDown: 59,
			timer: null,
			isCountdownEnd: false, // 标记倒计时是否结束
			isCodeError: false, // 验证码错误状态
			showKeyboard: true, // 显示自定义键盘
			keyboardLayout: [
				['1', '2', '3'],
				['4', '5', '6'],
				['7', '8', '9']
			]
		};
	},
	computed: {
		formattedPhone() {
			return this.phoneNumber.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
		}
	},
	onLoad(options) {
		if (options.phone) {
			this.phoneNumber = options.phone;
		}
		this.startCountDown();
	},
  
	onUnload() {
		clearInterval(this.timer);
	},
	methods: {
		startCountDown() {
			clearInterval(this.timer);
			this.isCountdownEnd = false;
			this.timer = setInterval(() => {
				if (this.countDown <= 0) {
					clearInterval(this.timer);
					this.isCountdownEnd = true;
					return;
				}
				this.countDown--;
			}, 1000);
		},
		onClose() {
			uni.navigateBack();
		},
		onRegetCode() {
			if (this.isCountdownEnd) {
				uni.showLoading({ title: '发送中...' });
				setTimeout(() => {
					uni.hideLoading();
					this.countDown = 59;
					this.isCountdownEnd = false;
					this.startCountDown();
					uni.showToast({ title: '验证码已发送', icon: 'none' });
				}, 1000);
			}
		},
		// 验证码输入处理
		onKeyClick(key) {
			if (this.verificationCode.length < 4) {
				this.verificationCode += key;
				this.isCodeError = false; // 输入时重置错误状态
				if (this.verificationCode.length === 4) {
					this.submitVerificationCode();
				}
			}
		},
		// 删除验证码
		onDelete() {
			if (this.verificationCode.length > 0) {
				this.verificationCode = this.verificationCode.slice(0, -1);
			}
		},

		// 验证码验证
		async submitVerificationCode() {
			uni.showLoading({ title: '登录中...' });
			console.log('验证码:', this.verificationCode);
			try {
				// 发送POST请求到登录接口
				const res = await request({
					url: 'User/mobilelogin',
					method: 'POST',
					data: {
						mobile: this.phoneNumber,
						scene: uni.getStorageSync('scene'),
						captcha: this.verificationCode
					}
				});
				// 处理响应数据
				if (res.code === 1) {
					console.log("登录成功",res);

					// 登录成功 - 存储token到本地
					uni.setStorageSync('token', res.data.userinfo.token);
					uni.setStorageSync('uid', res.data.userinfo.id);
					uni.setStorageSync('userinfo', res.data.userinfo);
					uni.showToast({ title: '登录成功', icon: 'success' });

					// 2秒后跳转首页
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/index-new/index' });
					}, 2000);
				} else if (res.code === 0) {
					// 验证码错误
					this.isCodeError = true;
					uni.showToast({ 
						title: '验证码错误，请重新输入', 
						icon: 'none', 
						duration: 2000,
						complete: () => {
							// 弹窗消失后恢复待输入状态
							setTimeout(() => {
								this.isCodeError = false;
								this.verificationCode = '';
							}, 300);
						}
					});
				}
			} catch (error) {
				// 请求失败处理
				uni.showToast({ title: '网络错误，请稍后重试', icon: 'none', duration: 2000 });
				console.error('登录请求失败:', error);
			} finally {
				uni.hideLoading();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.verify-code-page {
	padding: 70rpx;
	background-color: #fff;
	min-height: 100vh;
	box-sizing: border-box;
	position: relative;

	.close-btn {
		position: absolute;
		top: 107rpx;
		left: 40rpx;
		width: 40rpx;
		height: 40rpx;
	}

	.title {
		font-weight: 500;
		font-size: 54rpx;
		color: #0E1C37;
		margin-top: 197rpx;
		margin-bottom: 20rpx;
	}

	.tips {
		font-size: 30rpx;
		color: #A3A6B7;
		margin-bottom: 80rpx;
	}

	.code-input-box {
		position: relative;
		display: flex;
		justify-content: space-between;
		width: 100%;
		margin-bottom: 30rpx;
		height: 100rpx;



		.code-item {
			width: 80rpx;
			height: 100rpx;
			border-bottom: 2rpx solid #D0D4D7;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;

			// 动态激活样式
			&.active {
				border-bottom: 2rpx solid #0E1C37;
			}

			&.filled {
				border-bottom: 2rpx solid #0E1C37;
			}

			&.error {
				border-bottom: 2rpx solid #ff3333;
				background: rgba(255, 51, 51, 0.05);
				
				.code-text {
					color: #ff3333;
					animation: shake 0.3s ease-in-out;
				}
			}

			.code-text {
				font-size: 44rpx;
				color: #000;
				transition: color 0.2s ease;
			}

			.cursor {
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 2rpx;
				height: 40rpx;
				background: #000;
				z-index: 20;
			}
		}
	}

	.count-down {
		display: flex;
		justify-content: flex-end;

		font-size: 30rpx;
		color: #A3A6B7;


		text:last-child {
			color: #1890FF;
		}
	}

	.custom-keyboard {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #f5f5f5;
		padding: 20rpx 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);

		.keyboard-row {
			display: flex;
			justify-content: space-around;
			margin-bottom: 20rpx;

			.key {
				width: 200rpx;
				height: 80rpx;
				background-color: #fff;
				border-radius: 10rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 36rpx;
				color: #333;
				box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);

				&.delete {
					background-color: #e0e0e0;
					font-size: 30rpx;
				}

				&.empty {
					background-color: transparent;
					box-shadow: none;
				}
			}
		}
	}
}

@keyframes shake {
	0%, 100% {
		transform: translateX(0);
	}
	25% {
		transform: translateX(-4rpx);
	}
	75% {
		transform: translateX(4rpx);
	}
}
</style>